<?php
/**
 * Created by PhpStorm.
 * User: windon
 * Date: 2018/6/3
 * Time: 14:53
 */

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class FriendModel extends Model
{
    protected $table = 'friend';
    protected $guarded= [''];

    public function friendUser(){
        return $this->hasOne('App\Models\User', 'id', 'friend_uid');
    }

    public function user(){
        return $this->hasOne('App\Models\User', 'id', 'uid');
    }

    /*
     * 获取列表
     * */
    public static function getListArr($where)
    {
        return self::where($where)->get();
    }

    /*
     * 获取单行
     * */
    public static function getRowsObj($where=[], $feild = '*')
    {
        return self::select($feild)->where($where)->first();
    }

    /*
    * 改变亲友状态
    * @$uid 用户id
    * @$friend_uid 被关注的用户id
    * @status : 1 加入黑名单  2 解除黑名单
    * */
    public static function change_status($userinfo, $friend_uid, $status)
    {
        $model = new FriendModel();
        $sql = "select * from ".$model->getTable()." where ((uid={$userinfo->id} and friend_uid={$friend_uid}) or (uid={$friend_uid} and friend_uid={$userinfo->id}))";
        $list = DB::select($sql);
        if(!empty($list)){
            foreach ($list as $value){
                // 加入黑名单    $value->status：0 无效  1 正常
                if($status == 1){
                    if($value->status == '1')
                        $channel_friend = self::where('id', $value->id)->update(['status' => 0]);
                }
            }
        }
        $friend_apply_model = new FriendApply();

        $delete_sql = "delete from ".$friend_apply_model->getTable()." where ((uid={$userinfo->id} and apply_uid={$friend_uid}) or (uid={$friend_uid} and apply_uid={$userinfo->id}))";
        DB::delete($delete_sql);
        return true;
    }

    /*
     * 是否亲友
     * */
    public static function is_friend($uid, $friend_uid)
    {
        if(!empty($uid) && !empty($friend_uid)){
            $key = 'user:is_friend:u_'.$uid.'_f_'.$friend_uid;
            if(!empty(Redis::get($key)))
                return true;

            $rows = self::select('id')->where([['uid', '=', $uid], ['friend_uid', '=', $friend_uid], ['status', '=', '1']])->first();
            if(!empty($rows)){
                $expires_in = rand(3600, 3600*24);
                Redis::setex($key, $expires_in, 1);
                return true;
            }
        }
        return false;
    }

}